﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Input;

namespace ShapeDemo
{
    public class DataIntoXML
    {
        private PolygonDrawer pgnDrawer;

        public DataIntoXML(PolygonDrawer pgn)
        {
            pgnDrawer = pgn;
        }
        
        public void Save(string filename)
        {
            string strpolygon = ASPNETX_Adapter.SerializePolygon(pgnDrawer.PolygonCollection);

            StreamWriter swPolygon = new StreamWriter(filename + "polygon.xml");
            swPolygon.Write(strpolygon);
            swPolygon.Dispose();
        }

        public bool Load(string filename)
        {
            bool result=false;
            
            pgnDrawer.PolygonCollection = new List<ASPNETX_WPFPolygon>();

            //pgnDrawer.PolygonCanvas.Children.Clear();


            FileInfo textFile;
            StreamReader sr;

            try
            {
                //----Polygon
                textFile = new FileInfo(filename + "polygon.xml");
                sr = textFile.OpenText();

                pgnDrawer.PolygonCollection = ASPNETX_Adapter.DeSerializePolygon(sr.ReadToEnd());

                sr.Dispose();

                foreach (ASPNETX_WPFPolygon item in pgnDrawer.PolygonCollection)
                {
                    //item.PolygonBody.ToolTip = item.CommonProperty.Content + " " + item.CommonProperty.Detail;
                    item.PolygonBody.MouseEnter += new MouseEventHandler(pgnDrawer.ShowTooltipEvt);
                    item.PolygonBody.MouseMove += new MouseEventHandler(pgnDrawer.MoveTooltipEvt);
                    item.PolygonBody.MouseLeave += new MouseEventHandler(pgnDrawer.HideTooltipEvt);
                    pgnDrawer.PolygonCanvas.Children.Add(item.PolygonBody);
                }


                result=true;
            }
            catch
            {
                
            }

            return result;
        }
    }

    public class SimpleSerializer
    {
        public static string Serialize<T>(T t)
        {
            using (StringWriter sw = new StringWriter())
            {
                XmlSerializer xz = new XmlSerializer(t.GetType());
                xz.Serialize(sw, t);
                return sw.ToString();
            }
        }

        public static object Deserialize(Type type, string s)
        {
            using (StringReader sr = new StringReader(s))
            {
                XmlSerializer xz = new XmlSerializer(type);
                return xz.Deserialize(sr);
            }
        }
    }
}
